import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'
import type { RequestInterceptors, RequestConfig } from './types'

class Request {
	// 请求对象
	requestInstance: AxiosInstance
	// 拦截器对象
	interceptorsObj?: RequestInterceptors

	constructor(config: RequestConfig) {
		this.requestInstance = axios.create(config)
		this.interceptorsObj = config.interceptors

		this.createRequestInterceptors()

		// 使用拦截器
		this.requestInstance.interceptors.request.use(
			this.interceptorsObj?.requestInterceptors,
			this.interceptorsObj?.requestInterceptorsCatch,
		)
		this.requestInstance.interceptors.response.use(
			this.interceptorsObj?.responseInterceptors,
			this.interceptorsObj?.responseInterceptorsCatch,
		)

		this.createResponseInterceptors()
	}

	/**
	 * @description 配置全局请求拦截器
	 */
	private createRequestInterceptors() {
		this.requestInstance.interceptors.request.use(
			(res: AxiosRequestConfig) => {
				console.log('请求经过全局拦截器')
				return res
			},
			(error: any) => error,
		)
	}

	/**
	 * @description 配置全局响应拦截器
	 */
	private createResponseInterceptors() {
		this.requestInstance.interceptors.response.use(
			(res: AxiosResponse) => {
				console.log('响应经过全局拦截器')
				return res
			},
			(error: any) => error,
		)
	}

	request<T>(requestConfig: RequestConfig): Promise<T> {
		return new Promise((resolve, reject) => {
			if (requestConfig.interceptors?.requestInterceptors)
				requestConfig =
					requestConfig.interceptors.requestInterceptors(
						requestConfig,
					)
			this.requestInstance
				.request<any, T>(requestConfig)
				.then(res => {
					if (requestConfig.interceptors?.responseInterceptors)
						res =
							requestConfig.interceptors.responseInterceptors<T>(
								res,
							)
					resolve(res)
				})
				.catch(error => reject(error))
		})
	}
}

export default Request
